import { createRouter, createWebHashHistory } from 'vue-router';
import { systemStatusStore } from '@/store/system/status';
import { userStore } from '@/store/user';
import { hasPermissions } from '@/permission';
import { ElMessage } from 'element-plus';
import constantRoutes from './router-list';

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
});

router.beforeEach(async (to, from, next) => {
  if (!to.name) {
    //页面不存在
    next('/404');
    ElMessage.error('页面不存在');
  }
  if (to.meta?.permissions) {
    //需要权限
    if (!userStore().user.token) {
      //用户信息为空，到后端获取用户信息，并存到storage
      systemStatusStore().routerToPtah = to.fullPath;
      await userStore().login();
      systemStatusStore().routerToPtah = null;
      next(to.fullPath);
      //若获取失败则会跳转到登录页面，此处不会继续往下执行
      //若成功获取用户信息，此处继续往下执行
    } else if (hasPermissions(to.meta?.permissions as string[])) {
      //拥有权限，直接进入
      next();
    } else {
      //没有权限，阻止跳转
      ElMessage.error('no permission');
      next(from.fullPath);
      return;
    }
  } else {
    //无需权限，直接进入
    next();
  }
});

export default router;
